﻿using System;
using System.ComponentModel;
using System.Data;
using System.Web.Services;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Configuration;
using System.DirectoryServices;
using System.Data.Common;
using System.IO;
using System.IO.Compression;

namespace Shuba.Web.ws
{
    /// <summary>
    /// Summary description for sinct
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class sinct : System.Web.Services.WebService
    {
        [WebMethod]
        public string CheckLDAPSPADAUser(string LoginUser, string LoginPass, string Unit)
        {
            Shuba.Framework.Encryption Encryption = new Shuba.Framework.Encryption();

            string UserUnitCode = "~";
            string SPADADBEncCode = Encryption.Decrypt(ConfigurationManager.AppSettings["enc.code.spada"]);
            string SPADAAppCode = ConfigurationManager.AppSettings["app.code.spada"];

            if (IsLDAPUser(LoginUser, LoginPass))
            {
                object result;
                Database db = DBConn.CreateDatabase();

                DbCommand cmd = db.GetStoredProcCommand(@"WS_CheckLDAPSPADAUser_ENH2B3");

                db.AddInParameter(cmd, "@APP_ID", DbType.String, SPADAAppCode);
                db.AddInParameter(cmd, "@NIP", DbType.String, LoginUser);
                db.AddInParameter(cmd, "@BRANCH_ID", DbType.String, Unit);
                result = db.ExecuteScalar(cmd);

                string unit = result == null ? "na" : Convert.ToString(result);
                unit = unit == "" ? "na" : unit;
                UserUnitCode = unit + "," + SPADADBEncCode;
                return UserUnitCode;
            }
            else
            {
                return UserUnitCode + "," + SPADADBEncCode;
            }
        }

        bool IsLDAPUser(string LDAPUser, string LDAPPass)
        {
            if (basePage.ByPassAD())
                return true; //FOR TESTING PURPOSE ONLY
 
            string LDAPServer = ConfigurationManager.AppSettings["ldap"];

            DirectoryEntry entry = new DirectoryEntry(LDAPServer, LDAPUser, LDAPPass);
            try
            {
                string EName = entry.Name; //Untuk Trap Error (LDAP tidak dapat) atau berhasil

                return true;
            }
            catch
            {
                return false;
            }
        }

        [WebMethod]
        public byte[] GetSpadaUpdate(string UNIT, string VERSION)
        {
            Database db = DBConn.CreateDatabase();

            DbCommand cmd = db.GetStoredProcCommand(@"WS_GetSpadaUpdate_ENH2B3");

            db.AddInParameter(cmd, "@UNIT_CODE", DbType.String, UNIT);
            db.AddInParameter(cmd, "@VERSION", DbType.String, VERSION);

            return TransformIntoBytes(db.ExecuteDataSet(cmd));
        }

        byte[] TransformIntoBytes(DataSet ds)
        {
            byte[] data;
            MemoryStream memStream = new MemoryStream();
            GZipStream zipStream = new GZipStream(memStream, CompressionMode.Compress);
            ds.WriteXml(zipStream, XmlWriteMode.WriteSchema);
            zipStream.Close();
            data = memStream.ToArray();
            memStream.Close();
            return data;
        }

        [WebMethod]
        public bool CheckService()
        {
            return true;
        }

        [WebMethod]
        public bool UpdateIsDownload(string LOGIN_USER, string UNIT_CODE, string VERSION, string FILE_NAME, string PC_NAME)
        {
            Database db = DBConn.CreateDatabase();

            DbCommand cmd = db.GetSqlStringCommand(@"UPDATE TBL_BRANCH_SPADA_FILE_TMP 
            SET DOWNLOAD_BY = @DOWNLOAD_BY
                ,UPDATE_BY = @UPDATE_BY
                ,UPDATE_DATE = GETDATE()
            WHERE BRANCH_ID = @BRANCH_ID 
                AND PC_NAME = @PC_NAME
                AND VERSION = @VERSION 
                AND [FILE_NAME] = @FILE_NAME
                AND DOWNLOAD_DATE = GETDATE()

            IF @@ROWCOUNT = 0
            INSERT INTO [TBL_BRANCH_SPADA_FILE_TMP]
                ([BRANCH_ID],[PC_NAME],[VERSION]
               ,[FILE_NAME],[DOWNLOAD_BY],[DOWNLOAD_DATE]
               ,[ENTRY_BY],[ENTRY_DATE],[UPDATE_BY]
               ,[UPDATE_DATE])
            VALUES (@BRANCH_ID,@PC_NAME,@VERSION
               ,@FILE_NAME,@DOWNLOAD_BY,GETDATE()
               ,@ENTRY_BY,GETDATE(),@UPDATE_BY
               ,GETDATE())");

            db.AddInParameter(cmd, "@BRANCH_ID", DbType.String, UNIT_CODE ?? "");
            db.AddInParameter(cmd, "@PC_NAME", DbType.String, PC_NAME ?? "");
            db.AddInParameter(cmd, "@VERSION", DbType.String, VERSION ?? "");
            db.AddInParameter(cmd, "@FILE_NAME", DbType.String, FILE_NAME ?? "");
            db.AddInParameter(cmd, "@DOWNLOAD_BY", DbType.String, LOGIN_USER ?? "");
            db.AddInParameter(cmd, "@ENTRY_BY", DbType.String, LOGIN_USER ?? "");
            db.AddInParameter(cmd, "@UPDATE_BY", DbType.String, LOGIN_USER ?? "");
            db.ExecuteNonQuery(cmd);

            return true;
        }
    }
}